package com.code.telegram.services.impl;

import com.code.models.robot.ChatMessageNums;
import com.code.telegram.daos.task.ChatMessageNumsMapper;
import com.code.telegram.daos.task.RobotChatMapper;
import com.code.telegram.models.RobotChat;
import com.code.telegram.services.RobotChatService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * 与机器人聊天的用户服务实现类
 *
 * @author xiaoyaowang
 */
@Service
public class RobotChatServiceImpl implements RobotChatService {

    @Resource
    RobotChatMapper robotChatMapper;

    @Resource
    ChatMessageNumsMapper chatMessageNumsMapper;

    @Override
    public RobotChat insertRobotChat(RobotChat robotChat) {
        String chatId = robotChat.getChatId();
        Integer existCount = robotChatMapper.existsRobotChatByChatId(chatId);
        if (null == existCount) {
            robotChat.setDeleted(0);
            robotChat.setCreatedAt(new Date());
            robotChat.setUpdatedAt(new Date());
            robotChatMapper.insert(robotChat);
        }
        return robotChatMapper.getRobotChatByChatId(chatId);
    }

    @Override
    public int incrementChatMessageNums(String chatId, String firstName,
                                        String lastName, String userName) {
        String currentDate = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDate.now());
        ChatMessageNums chatMessageNumDb = chatMessageNumsMapper.getChatMessageNumsByChatId(chatId, currentDate);
        if (null == chatMessageNumDb) {
            ChatMessageNums chatMessageNum = new ChatMessageNums();
            chatMessageNum.setChatId(chatId);
            chatMessageNum.setMessageNums(1);
            chatMessageNum.setFirstName(firstName);
            chatMessageNum.setLastName(lastName);
            chatMessageNum.setUserName(userName);
            chatMessageNum.setDeleted(0);
            chatMessageNum.setVersion(0);
            chatMessageNum.setCurrentDay(currentDate);
            chatMessageNum.setCreatedAt(new Date());
            chatMessageNum.setUpdatedAt(new Date());
            return chatMessageNumsMapper.insert(chatMessageNum);
        } else {
            return chatMessageNumsMapper.incrementChatMessageNums(chatMessageNumDb.getId(), chatMessageNumDb.getVersion(), new Date());
        }
    }
}
